<template>
  <div class="center">
    <n-card :bordered="false" class="mt-4 proCard" size="small" :segmented="{ content: 'hard' }">
      <div class="formClass">
        <n-form
          :model="formValue"
          :size="size"
          ref="formRef"
          label-placement="left"
          label-align="left"
          :label-width="100"
        >
          <n-space justify="space-between">
            <n-h6 prefix="bar" type="success">配置编辑&新增角色</n-h6>
          </n-space>
          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi
              v-for="(item, index) in ItemList"
              :key="index"
              :span="item.span"
              :label="`${item.label}:`"
            >
              <component
                :is="item.type"
                v-model:value="formValue[item.enName]"
                :options="item.options"
                :clearable="item.clearable"
                :check-strategy="item.checkStrategy"
                :checkable="item.checkable"
                :cascade="item.cascade"
                :multiple="item.multiple"
                :disabled="item.disabled"
                :src="item.src"
                :size="item.size"
                :style="{ width: item.width }"
              >
              </component>
            </n-form-item-gi>
          </n-grid>
          <n-space style="justify-content: center;">
            <n-button type="primary" @click="preservation">保存</n-button>
            <n-button @click="cancel">取消</n-button>
          </n-space>
        </n-form>
      </div>
    </n-card>
  </div>
</template>

<script>
import { defineComponent, ref,onMounted } from 'vue';
import { useMessage } from 'naive-ui';
import { NConfigProvider, NCascader, NInput, NDatePicker, NSpace } from 'naive-ui';
import { fetchAuthListPage, fetchMenuList,addRole } from '@/api/Role/index'; //导入接口文件
import { useRoute,useRouter } from 'vue-router';
export default defineComponent({
  name:'addRole',
  components: {
    NConfigProvider,
    NInput,
    NDatePicker,
    NSpace,
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const formRef = ref(null);
    const message = useMessage();
    const type = ref(true);
    const ItemList = ref([
      {
        label: '角色名称',
        type: 'N-input',
        enName: 'roleName',
        span: 24,
        clearable: true,
        disabled: false,
        size: 'small',
      },
      {
        label: '分配菜单',
        type: 'N-tree-select',
        enName: 'menuList',
        checkStrategy:'all',
        multiple: true,
        clearable: true,
        checkable: true,
        cascade: true,
        options: [],
        span: 24,
        disabled: false,
        size: 'small',
      },
      {
        label: '分配额外权限',
        type: 'N-tree-select',
        enName: 'authList',
        checkStrategy:'all',
        multiple: true,
        clearable: true,
        checkable: true,
        cascade: true,
        options: [],
        span: 24,
        disabled: false,
        size: 'small',
      },
    ]);
    const formValue = ref({});
    //编辑
    const edit = () => {
      type.value = false;
      ItemList.value.map((res) => {
        return (res.disabled = false);
      });
    };
    onMounted(() => {
      jurisdiction();
      menu();
    });
    //获取权限列表
    const jurisdiction = async () => {
        const data = await fetchAuthListPage();
        const options = data.list.map((res) => {
            return {
                label:res.authName,
                key:res.id
            }
        });
        ItemList.value.map((res) => {
            if(res.enName == 'authList'){
                res.options = options
            }
        })
    }
    
    //获取菜单列表
    const menuData = ref([])
    const ModelmenuData = ref([]);
    const menu = async () => {
        ModelmenuData.value = await fetchMenuList();
        //菜单处理
        ModelmenuData.value.map((res) => {
            if(res.parentId == '0'){
            menuData.value.push({
                label:res.menuName,
                key:res.id,
                id:res.id
            })
            }
        });

      let request = await DepartmentRecursion(menuData.value);
        ItemList.value.map((res) => {
            if(res.enName == 'menuList'){
                res.options = request
            }
        })
    };

    //菜单递归
    const DepartmentRecursion = async (data) => {
      try {
        for(var i = 0; i < data.length; i ++){
            for (var j = 0; j < ModelmenuData.value.length; j++) {
              if(ModelmenuData.value[j].parentId == data[i].id){
                if (data[i].hasOwnProperty('children')) {
                  data[i].children.push({
                    label:ModelmenuData.value[j].menuName,
                    key:ModelmenuData.value[j].id,
                    id:ModelmenuData.value[j].id
                  })
                } else {
                  data[i].children = []
                  data[i].children.push({
                    label:ModelmenuData.value[j].menuName,
                    key:ModelmenuData.value[j].id,
                    id:ModelmenuData.value[j].id
                  })
                }
              }
            }
          if(data[i].children){
            // children若不为空数组，则继续递归调用本方法
            DepartmentRecursion(data[i].children);
          }
        }
      } catch(e){
        console.log(e)
      }
      return data
    };

    //保存
    const preservation = async () => {
        formValue.value = { ...formValue.value,...route.params}
        await addRole(formValue.value)
        console.log(formValue.value)
    }
    //取消
    const cancel = () => {
        router.push({ name: 'roleManagement'});
    }
    return {
      ModelmenuData,
      menuData,
      formRef,
      preservation,
      cancel,
      edit,
      jurisdiction,
      menu,
      size: ref('medium'),
      ItemList,
      formValue,
      type,
      handleValidateButtonClick(e) {
        e.preventDefault();
        formRef.value.validate((errors) => {
          if (!errors) {
            message.success('验证成功');
          } else {
            console.log(errors);
            message.error('验证失败');
          }
        });
      },
    };
  },
});
</script>
<style lang="less" scoped>
.center :deep .n-avatar {
  position: relative;
  bottom: 15px;
}
.formClass {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
